package com.fcgzs.config;

import com.fcgzs.common.utils.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Auther: ljj
 * @Date: 2021/08/23 15:18
 * @Description:
 */
public class JwtCheckGatewayFilterFactory extends AbstractGatewayFilterFactory<JwtCheckGatewayFilterFactory.Config> {

    // 这里需要将自定义的config传过去，否则会报告ClassCastException
    public JwtCheckGatewayFilterFactory() {
        super(Config.class);
    }
    @Override
    public GatewayFilter apply(Config config) {
        return new InnerFilter(config);
    }

    public class InnerFilter implements GatewayFilter, Ordered {

        private Config config;

        //把配置注入构造函数
        InnerFilter(Config config) {
            this.config = config;
        }

        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            //获取request,response对象
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();

            //从request对象中获取令牌
            String token = request.getHeaders().getFirst("Authorization");
            if (StringUtils.isEmpty(token)) {
                response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
                return response.setComplete();
            }
            //如果令牌存在则校验令牌
            boolean flag = JWTUtil.checkJWT(token);
            if (flag) {
                return chain.filter(exchange);
            } else {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

        }

        @Override
        public int getOrder() {
            return 0;
        }
    }
    //创建一个内部类，配置过滤器属性
    public static class Config {

    }


}
